import 'package:getx_scaffold/getx_scaffold.dart';
import 'points_detail_state.dart';
import '../../../core/repository/default_api.dart';

class PointsDetailLogic extends GetxController {
  final state = PointsDetailState();
  final _api = DefaultApi();

  @override
  void onInit() {
    super.onInit();
    _loadPointsRecords();
  }

  /// 加载积分记录
  Future<void> _loadPointsRecords() async {
    try {
      state.isLoading.value = true;
      final response = await _api.queryShopPointsIncomeGet<Map<String, dynamic>>(
        pageNum: 1,
        pageSize: 100,
        isShowLoading: false,
      );

      if (response != null && response['code'] == 200) {
        final List<dynamic> rows = response['rows'] ?? [];
        
        // 计算总积分
        int totalPoints = 0;
        
        state.pointsRecords.value = rows.map((item) {
          final points = (item['points'] ?? 0) as int;
          totalPoints += points;
          
          return {
            'id': item['id'],
            'title': item['description'] ?? '',
            'points': points,
            'type': points >= 0 ? 'income' : 'expense',
            'time': item['createdAt'] ?? '',
            'sourceType': item['sourceType'],
            'sourceId': item['sourceId'],
          };
        }).toList();
        
        // 更新总积分（这里显示的是累计变化，实际应该从用户信息获取）
        state.totalPoints.value = totalPoints.abs();
      }
    } catch (e) {
      Toast.show('加载积分明细失败');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 切换tab
  void changeTab(int index) {
    state.selectedTabIndex.value = index;
  }

  /// 获取过滤后的记录
  List<Map<String, dynamic>> get filteredRecords {
    if (state.selectedTabIndex.value == 0) {
      // 全部
      return state.pointsRecords;
    } else if (state.selectedTabIndex.value == 1) {
      // 积分收入
      return state.pointsRecords.where((r) => r['type'] == 'income').toList();
    } else {
      // 积分支出
      return state.pointsRecords.where((r) => r['type'] == 'expense').toList();
    }
  }
}
